package cn.yunyichina.provider.base.service.impl;

import cn.yunyichina.provider.base.dao.*;
import cn.yunyichina.provider.base.entity.MedicalCard;
import cn.yunyichina.provider.base.entity.PersonalUserFamily;
import cn.yunyichina.provider.base.utils.DruidUtil;
import cn.yunyichina.provider.base.utils.IdCardUtils;
import cn.yunyichina.provider.base.utils.OrgCodeMap;
import cn.yunyichina.provider.base.vo.*;
import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.annotation.validate.Validator;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.*;
import cn.yunyichina.provider.iface.entity.base.BindCardVo;
import cn.yunyichina.provider.iface.entity.base.MedicalCardVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.base.OrgApp;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.hisiface.base.CreateCardVo;
import cn.yunyichina.provider.iface.entity.hisiface.base.CreateCardVoResponse;
import cn.yunyichina.provider.iface.entity.hisiface.base.PatientVo;
import cn.yunyichina.provider.iface.entity.hisiface.base.PatientVoResponse;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.IDUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 绑卡服务
 *
 * @author adriftor
 */
@Service("bindcardServiceImpl")
public class BindCardServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(BindCardServiceImpl.class);


    @Autowired
    private MedicalCardDao medicalCardDao;

    @Autowired
    private PersonalUserDao personalUserDao;

    @Autowired
    private PersonalUserOpenidDao personalUserOpenidDao;

    @Autowired
    private PersonalUserRelationDao personalUserRelationDao;
    @Autowired
    private PersonalUserFamilyDao personalUserFamilyDao;

//    @Resource
//    private HospitalServiceImpl hospitalServiceImpl;

    @Resource
    private OrgServiceImpl orgServiceImpl;

    @Resource
    private OrgAppServiceImpl orgAppServiceImpl;

    public static DateFormat YYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
    public static DateFormat YYYYMMDD8 = new SimpleDateFormat("yyyyMMdd");

    public ResponseObject deleteBindCard(String strData) {
        logger.info("绑卡 addBindCard strData: " + strData);
        ResponseObject response = new ResponseObject();
        AddBindCardRequest requestVo = JsonUtils.parseObject(strData, AddBindCardRequest.class);

        if (StringUtils.isBlank(requestVo.getMedicalCardId())) {
            response.setResultCodeAndMessage("1002", "就诊卡id medicalCardId 不能为空");
            return response;
        }
        try {
            medicalCardDao.updateMedicalCardStateById(requestVo.getMedicalCardId());
            response.setResultCodeAndMessage("0", "移除就诊卡成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1998", "移除就诊卡失败");
        }

        return response;
    }

    @Transactional
    public ResponseObject addBindCard(String strData) {
        logger.info("绑卡 addBindCard strData: " + strData);
        ResponseObject response = new ResponseObject();
        AddBindCardRequest requestVo = JsonUtils.parseObject(strData, AddBindCardRequest.class);
        MedicalCard medicalCard = null;
        if (StringUtils.isBlank(requestVo.getPatCardNo()) || StringUtils.isBlank(requestVo.getPatIdNo()) || StringUtils.isBlank(requestVo.getUserId())||StringUtils.isBlank(requestVo.getPatName())) {
            response.setResultCodeAndMessage("1002", "参数缺失，请检查");
            return response;
        }
        /**检查身份证格式：包括二代，港澳，台湾*/
        if (!StringUtils.isBlank(requestVo.getPatIdNo())) {
            if (!IdCardUtils.validateCard(requestVo.getPatIdNo())) {
                response.setResultCodeAndMessage("1002", "身份证格式错误");
                return response;
            }
        }

        try {
            medicalCard = medicalCardDao.selectUniqueMedicalCard(requestVo.getHospitalCode(), requestVo.getPatCardNo(), requestVo.getPatCardType(),requestVo.getUserId(),requestVo.getFamilyId());
            if (medicalCard != null) {
                /** 该卡属于解绑状态，将该卡设置为绑定*/
                medicalCard.setIdCardType(requestVo.getPatIdType());
                medicalCard.setIdCardNo(requestVo.getPatIdNo());
                medicalCard.setPatMobile(requestVo.getPatMobile());
                medicalCard.setPatName(requestVo.getPatName());
                medicalCard.setEnableFlag(new Short("1"));
                medicalCardDao.update(medicalCard);
                response.setResultCodeAndMessageAndResult("0", "成功", buildMedicalCardResponseVo(medicalCard));
                return response;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1998", "绑卡失败");
            return response;
        }


        try {
            /**入库绑卡信息开始*/
            medicalCard = buildMedicalCard(requestVo);
            medicalCardDao.insert(medicalCard);
            /**入库绑卡信息结束*/
            response.setResultCodeAndMessageAndResult("0", "成功",buildMedicalCardResponseVo(medicalCard));
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("1998", "绑卡失败");
            return response;
        }
        return response;
    }

    private MedicalCardResponseVo buildMedicalCardResponseVo(MedicalCard medicalCard){
        MedicalCardResponseVo result = new MedicalCardResponseVo();
        result.setId(medicalCard.getId());
        result.setPatIdNo(medicalCard.getIdCardNo());
        result.setPatIdType(medicalCard.getIdCardType());
        result.setPatCardNo(medicalCard.getMedicalCardNo());
        result.setPatCardType(medicalCard.getMedicalCardType());
        result.setPatName(medicalCard.getPatName());
        result.setPatMobile(medicalCard.getPatMobile());
        result.setUserId(medicalCard.getPatId());
        result.setFamilyId(medicalCard.getFamilyId());
        result.setPatBirth(medicalCard.getPatBirth());
        result.setHospitalCode(medicalCard.getOrgCode());
        result.setHospitalId(medicalCard.getOrgId());
        result.setHospitalName(medicalCard.getOrgName());
        result.setPatAddress(medicalCard.getPatAddress());
        result.setAdmissionNo(medicalCard.getAdmissionNo());
        result.setPatSex(medicalCard.getPatSex());
        result.setHisPatId(medicalCard.getHisPatId());
        result.setDataSource(medicalCard.getDataSource());
        result.setInsuranceCardNo(medicalCard.getInsuranceCardNo());
        result.setIsInsurance(medicalCard.getIsInsurance());
        result.setPatAge(medicalCard.getPatAge());
        result.setGuardIdCardNo(medicalCard.getGuardIdCardNo());
        result.setGuardIdCardType(medicalCard.getGuardIdCardType());
        result.setGuardName(medicalCard.getGuardName());
        result.setGuardMobile(medicalCard.getGuardMobile());
        return result;
    }


    private MedicalCard buildMedicalCard(AddBindCardRequest requestVo) {
        MedicalCard medicalCard = new MedicalCard();

        Org org = orgServiceImpl.getOrgByCode(requestVo.getHospitalCode());

        medicalCard.setId(IDUtils.getUUID32());
        /**组织信息，此即医院信息*/
        medicalCard.setOrgCode(requestVo.getHospitalCode());
        medicalCard.setOrgId(org.getId());
        medicalCard.setOrgName(org.getOrgName());

        /**患者基本信息*/
        //personalUser表的ID
        medicalCard.setPatId(requestVo.getUserId());
        medicalCard.setFamilyId(requestVo.getFamilyId());
        //患者姓名
        medicalCard.setPatName(requestVo.getPatName());
        //1-男\r\n            2-女\r\n
        if(requestVo.getPatIdType() !=null && requestVo.getPatIdType()!=1){
            /**港澳 台湾计算性别*/
            String sex = IdCardUtils.validateIdCard10(requestVo.getPatIdNo())[1];
            medicalCard.setPatSex((short) ("M".equalsIgnoreCase(sex) ? 1 : 2));
        }else {
            medicalCard.setPatSex((short) ("M".equalsIgnoreCase(IdCardUtils.getGenderByIdCard(requestVo.getPatIdNo())) ? 1 : 2));
        }

        if (StringUtils.isNotEmpty(requestVo.getPatIdNo())&&requestVo.getPatIdType()!=1) {
            medicalCard.setPatAge(IdCardUtils.getAgeByIdCard(requestVo.getPatIdNo()));
        } else {
            //小孩的情况
            medicalCard.setPatAge(requestVo.getPatAge());
        }
        //生日
        medicalCard.setPatBirth(requestVo.getPatBirth());
        //手机
        medicalCard.setPatMobile(requestVo.getPatMobile());
        medicalCard.setPatAddress(requestVo.getPatAddress());
        //HIS端的patId
        medicalCard.setHisPatId(requestVo.getHisPatId());

        //证件类型\r\n            1：二代身份证， \r\n            2：港澳居民身份证， \r\n            3：台湾居民身份证， \r\n            4：护照\r\n    S
        medicalCard.setIdCardType(requestVo.getPatIdType() != null ? 1 : requestVo.getPatIdType());
        //身份证
        medicalCard.setIdCardNo(requestVo.getPatIdNo());
        /**诊疗卡号和类型*/
        medicalCard.setMedicalCardType(requestVo.getPatCardType());
        medicalCard.setMedicalCardNo(requestVo.getPatCardNo());
        //0-绑定\r\n            1-建档
        medicalCard.setBindWay(requestVo.getBindWay());

        //1-微信\r\n    2-支付窗\r\n            3-APP应用
        medicalCard.setBindSourceFlag(requestVo.getPlatformType().shortValue());

        /**监护者信息*/
        medicalCard.setGuardId(requestVo.getGuardId());
        medicalCard.setGuardName(requestVo.getGuardName());
        medicalCard.setGuardIdCardType(requestVo.getGuardIdCardType() == null ? 1 : requestVo.getGuardIdCardType());
        medicalCard.setGuardIdCardNo(requestVo.getGuardIdCardNo());
        medicalCard.setGuardMobile(requestVo.getGuardMobile());
        medicalCard.setGuardAddress(requestVo.getGuardAddress());

        medicalCard.setEnableFlag((short) 1);
        medicalCard.setBeginCreatedTime(DateUtils.dateToString(new Date()));
        medicalCard.setCreatedTime(DateUtils.dateToString(new Date()));

        return medicalCard;
    }
    private String checkRequestData(QueryPatientVo requestVo){
        String errMsg ="";
        if(StringUtils.isEmpty(requestVo.getFamilyId())) {
            if (requestVo.getPatCardType() == null){
                errMsg ="卡类型不能为空";
                return errMsg;
            }
            if (StringUtils.isBlank(requestVo.getPatCardNo())) {
                errMsg ="身份证或就诊卡不能为空";
                return errMsg;
            }
            if (requestVo.getPatCardType() == 5) {
                if (StringUtils.isBlank(requestVo.getPatName())) {
                    errMsg= "卡类型是身份证时,姓名不能为空";
                    return errMsg;
                }
                if (!IdCardUtils.validateCard(requestVo.getPatCardNo())) {
                    errMsg ="身份证格式错误";
                    return errMsg;
                }
            }
        }
        return errMsg;
    }

    private PatientVo buildPatientVo(QueryPatientVo requestVo){
        PatientVo patientVo = new PatientVo();
        patientVo.setHospitalCode(requestVo.getHospitalCode());
        patientVo.setPatCardNo(requestVo.getPatCardNo());
        patientVo.setPatName(requestVo.getPatName());
        patientVo.setPatCardType(requestVo.getPatCardType().toString());
        return patientVo;
    }
    private PatientVo buildPatientVo(QueryPatientVo requestVo,PersonalUserFamily personalUserFamily){
        PatientVo patientVo = new PatientVo();
        patientVo.setHospitalCode(requestVo.getHospitalCode());
        patientVo.setPatName(personalUserFamily.getUserName());
        if (requestVo.getPatCardType() !=null && requestVo.getPatCardType()==1 && StringUtils.isNotEmpty(requestVo.getPatCardNo())){
            patientVo.setPatCardNo(requestVo.getPatCardNo());
            patientVo.setPatCardType(requestVo.getPatCardType().toString());
        }else {
            patientVo.setPatCardNo(personalUserFamily.getIdCardNo());
            patientVo.setPatCardType("5");
        }

        return patientVo;
    }

    /**
     * 查询患者信息
     *
     * @param strData
     * @return
     */
    public ResponseObject queryBindCardPatient(String strData) {
        logger.info("患者信息查询原始入参strData ={}",strData);
        ResponseObject response = new ResponseObject();

        try {
            QueryPatientVo requestVo = JsonUtils.parseObject(strData, QueryPatientVo.class);
            try {
                //信息校验
                String errMsg = checkRequestData(requestVo);
                if (StringUtils.isNotEmpty(errMsg)){
                    response.setResultCodeAndMessage("1001",errMsg);
                    return response;
                }

            }catch (Exception e){
                logger.error("信息校验系统异常",e);
                response.setResultCodeAndMessage("1998","信息校验系统异常");
                return response;
            }

            PatientVo patientVo = null;
            if (StringUtils.isNotEmpty(requestVo.getFamilyId())){
                PersonalUserFamily personalUserFamily = personalUserFamilyDao.selectById(requestVo.getFamilyId());
                if (personalUserFamily == null){
                    response.setResultCodeAndMessage("1001","患者信息查询通过family_id 查询不到对应就诊人");
                    return response;
                }
                patientVo = buildPatientVo(requestVo,personalUserFamily);
            }else {
                patientVo = buildPatientVo(requestVo);
            }

            PatientVoResponse patientVoResponse =null;
            try {
                logger.info("患者信息查询请求调度中心入参 patientVo ={}",new Object[]{JsonUtils.toJsonString(requestVo)});
                ResCommon<PatientVoResponse> commonPatientVoResponse = HisifaceService.getHisifaceClient().getPatient(patientVo);
                logger.info("患者信息查询调度中心出参 commonPatientVoResponse ={}",new Object[]{JsonUtils.toJsonString(commonPatientVoResponse)});
                if (!"0".equals(commonPatientVoResponse.getResultCode())) {
                    response.setResultCodeAndMessage("1998", "查询his失败");
                    return response;
                }
                patientVoResponse = commonPatientVoResponse.getResult();
                if (patientVoResponse == null) {
                    response.setResultCodeAndMessage("1001", "查询his 无数据返回");
                    return response;
                }
            } catch (Exception e) {
                logger.error("患者信息查询his异常",e);
                response.setResultCodeAndMessage("1998", "查询his系统异常");
                return response;
            }

            /**组装返回对象**/
            PatientResponseResult result = new PatientResponseResult();
            result.setPatIdNo(patientVoResponse.getPatIdNo());
            result.setPatIdType(patientVoResponse.getPatIdType());
            result.setPatType(patientVoResponse.getPatType());
            result.setHospitalCode(patientVoResponse.getHospitalCode());
            result.setPatMobile(patientVoResponse.getPatMobile());
            result.setPatName(patientVoResponse.getPatName());
            result.setPatCardNo(patientVoResponse.getPatCardNo());
            result.setPatSex(patientVoResponse.getPatSex());
            result.setPatBirth(patientVoResponse.getPatBirth());
            result.setPatAddress(patientVoResponse.getPatAddress());
            result.setHisPatId(patientVoResponse.getPatId());
            result.setAdmissionNo(patientVoResponse.getAdmissionNo());
            result.setExtendParams(patientVoResponse.getExtendParams());
            result.setGuardIdNo(patientVoResponse.getGuardIdNo());
            result.setGuardIdType(patientVoResponse.getGuardIdType());
            result.setGuardMobile(patientVoResponse.getGuardMobile());
            result.setGuardName(patientVoResponse.getGuardName());
            result.setPatCardType(patientVoResponse.getPatCardType());
            response.setResultCodeAndMessageAndResult("0", "成功", result);
            logger.info("患者信息查询返回出参 result ={}",new Object[]{JsonUtils.toJsonString(result)});
            return response;
        }catch (Exception e){
            logger.error("患者信息查询系统异常",e);
            response.setResultCodeAndMessage("-1","患者信息查询系统异常");
            return response;
        }
    }

    /**
     * 患者首建档
     *
     * @param strData
     * @return
     */

    public ResponseObject createBindCardPatient(String strData) {
        ResponseObject response = new ResponseObject();
        logger.info("患者首建档原始入参 strData",strData);
        CreatePatientVo requestVo = JsonUtils.parseObject(strData, CreatePatientVo.class);
        try {
            Validator.getInstance().validate(requestVo);
        } catch (ValidateException ex) {
            logger.info(" 数据校验失败 errMsg={}", ex.getMessage());
            logger.error("error", ex);
            response.setResultCodeAndMessage("1001", "数据校验失败:" + ex.getMessage() + "！");
            return response;
        }
        CreateCardVo createCardVo = new CreateCardVo();
        createCardVo.setHospitalCode(requestVo.getHospitalCode());
        createCardVo.setPatType(requestVo.getPatType() == null ? "1" : requestVo.getPatType().toString());
        createCardVo.setPatName(requestVo.getPatName());
        createCardVo.setPatSex(requestVo.getPatSex());
        createCardVo.setPatBirth(requestVo.getPatBirth());
        createCardVo.setPatAddress(requestVo.getPatAddress());
        createCardVo.setPatMobile(requestVo.getPatMobile());
        createCardVo.setPatIdType(requestVo.getPatIdType() == null ? "1" : requestVo.getPatIdType().toString());
        createCardVo.setPatIdNo(requestVo.getPatIdNo());
        createCardVo.setGuardIdType(requestVo.getGuardIdCardType() == null ? "1" : requestVo.getGuardIdCardType().toString());
        createCardVo.setGuardName(requestVo.getGuardName());
        createCardVo.setGuardIdNo(requestVo.getGuardIdCardNo());


        CreateCardVoResponse createCardVoResponse = null;
        try {
            logger.info("患者首建档给调度中心入参 createCardVo ={}",new Object[]{JsonUtils.toJsonString(createCardVo)});
            ResCommon<CreateCardVoResponse> commonCreateCardVoResponse = HisifaceService.getHisifaceClient().createCard(createCardVo);
            logger.info("患者首建档调度中心出参报文 commonCreateCardVoResponse ={} ",new Object[]{JsonUtils.toJsonString(commonCreateCardVoResponse)});
            if (!"0".equals(commonCreateCardVoResponse.getResultCode())) {
                response.setResultCodeAndMessage("1997", "患者首建档his失败");
                return response;
            }
            createCardVoResponse = commonCreateCardVoResponse.getResult();
            if (createCardVoResponse == null) {
                response.setResultCodeAndMessage("1001", "查询his 无数据返回");
                return response;
            }
        } catch (Exception e) {
           logger.error("患者首建档his系统异常");
            response.setResultCodeAndMessage("1998", "患者首建档his系统异常");
            return response;
        }

        Map<String ,String> resultMap = new HashMap<String,String>();
        resultMap.put("pat_card_no",createCardVoResponse.getPatCardNo());
        resultMap.put("pat_card_type",createCardVoResponse.getPatCardType());
        resultMap.put("his_pat_id",createCardVoResponse.getPatId());
        response.setResultCodeAndMessageAndResult("0", "成功", JsonUtils.toJsonString(resultMap));
        logger.info("患者首建档返回报文 response ={}",new Object[]{JsonUtils.toJsonString(response)});
        return response;
    }


    /**
     * 绑卡
     * yyt.base.bindcard.create
     *
     * @param data      BindCardVo对象
     * @param sessionid
     * @return MedicalCard
     */
    public MedicalCardVo createBindCard(String data, String sessionid) {
        try {
            logger.debug("bindCard:" + data);
            BindCardVo bindCardVo = JsonUtils.parseObject(data, BindCardVo.class);
            logger.debug("bindCardVo:" + JsonUtils.toJsonString(bindCardVo));
            if (StringUtils.isBlank(bindCardVo.getOpenId()) || bindCardVo.getPlatformType() == null || (StringUtils.isBlank(bindCardVo.getCardNo()) && StringUtils.isBlank(bindCardVo.getIdCard()))) {
                logger.error("bindCard1:参数信息不全");
                throw new CallException(ErrorCodeDefine.BIND_CARD_PARAM, "参数信息不全");
            }

            if (StringUtils.isBlank(bindCardVo.getCardNo()) && (StringUtils.isBlank(bindCardVo.getIdCard()) || StringUtils.isBlank(bindCardVo.getPatName()))) {
                logger.error("bindCard2:参数信息不全");
                throw new CallException(ErrorCodeDefine.BIND_CARD_PARAM, "参数信息不全");
            }

            //是否已经检查用户已经执行过绑定
            boolean hasCheckMedicalExist = false;

            if (bindCardVo.getCardType() != null && StringUtils.isNotEmpty(bindCardVo.getCardNo())) {

                hasCheckMedicalExist = true;

                //查询数据库是否已经有绑卡
                MedicalCardVo existMedicalCard = medicalCardDao.getMedicalCardByCardNo(bindCardVo.getHospitalCode(), bindCardVo.getCardNo(), (short) bindCardVo.getCardType().intValue());
                if (existMedicalCard != null) {
                    logger.warn("数据库已经存在绑卡记录:" + JsonUtils.toJsonString(existMedicalCard));
//					throw new CallException(ErrorCodeDefine.BIND_CARD_HAS_BINDED,"用户之前已经绑定");
                    return existMedicalCard;
                }
            }


            GetPatientInfoVoResponse hisPatient = null;
            if (StringUtils.isNotEmpty(bindCardVo.getCardNo())) {//有卡号
                logger.debug("bindCard:有诊疗卡号");

                //调用HIS患者信息查询接口
                hisPatient = queryHisPatUser(bindCardVo.getHospitalCode(), bindCardVo.getCardType(), bindCardVo.getCardNo(), bindCardVo.getPatName());

            } else {//无卡号，按身份证绑卡
                logger.debug("bindCard:身份证");
                //调用HIS患者信息查询接口
                hisPatient = queryHisPatUser(bindCardVo.getHospitalCode(), new Short("5"), bindCardVo.getIdCard(), bindCardVo.getPatName());
            }

            logger.debug("bindCard:patInfo" + JsonUtils.toJsonString(hisPatient));

            /**
             * 获取医院信息
             */
            JSONObject param = new JSONObject();
            param.put("hospital_code", bindCardVo.getHospitalCode());
            if (bindCardVo.getPlatformType() == 1) {
                param.put("app_code", "wechat");
            } else if (bindCardVo.getPlatformType() == 2) {
                param.put("app_code", "alipay");
            } else if (bindCardVo.getPlatformType() == 3) {
                param.put("app_code", "easyHealth");
            } else {
                param.put("app_code", "");
            }
//					HospitalCodeAndAppVo hospitalCodeAndAppVo = JsonUtils.parseObject(BaseService.callHumpFromInternal("yyt.base.hospital.appinfo.get", JsonUtils.toJsonString(param)).getResult(),HospitalCodeAndAppVo.class);
//					logger.debug("yyt.base.hospital.appinfo.get返回："+JsonUtils.toJsonString(hospitalCodeAndAppVo));
//			HospitalCodeAndAppVo hospitalCodeAndAppVo = hospitalServiceImpl.getHospitalAppInfo(JsonUtils.toJsonString(param), "");
//			logger.debug("appId信息："+JsonUtils.toJsonString(hospitalCodeAndAppVo));

            OrgApp orgApp = orgAppServiceImpl.getByAppCode(bindCardVo.getOrgAppCode());

            if (orgApp == null) {
                logger.debug("获取appId信息异常：调用参数" + JsonUtils.toJsonString(param));
                throw new CallException(ErrorCodeDefine.BIND_CARD_VALUE, "获取appId信息异常");
            }

            //是否进行建档
            boolean createCardFlag = false;

            //HIS没有患者信息，执行建档流程
            if (hisPatient == null) {

                logger.debug("bindCard:HIS患者信息接口返回数据为null值,执行建档");

                if (StringUtils.isBlank(bindCardVo.getIdCard()) || StringUtils.isBlank(bindCardVo.getPatName())) {
                    logger.debug("建档：身份证或姓名缺失");
                    throw new CallException(ErrorCodeDefine.BIND_CARD_PARAM, "建档：身份证或姓名缺失");
                }

                createCardFlag = true;

                //调用HIS建立患者建档接口
                CardRequest cardRequest = new CardRequest();

                //身份证号
                cardRequest.setPatIdNo(bindCardVo.getIdCard());

                //患者姓名
                cardRequest.setPatName(bindCardVo.getPatName());

                //证件类型，固定为身份证
                cardRequest.setPatIdType("1");

                //患者性别
                cardRequest.setPatSex(IdCardUtils.getGenderByIdCard(bindCardVo.getIdCard()));

                //出生日期
                cardRequest.setPatBirth(YYYYMMDD.format(YYYYMMDD8.parse(IdCardUtils.getBirthByIdCard(bindCardVo.getIdCard()))));

                //手机
                cardRequest.setPatMobile(bindCardVo.getPatMobile());

                JSONObject jsonCard = JsonUtils.parseObject(cardRequest);
                jsonCard.put("hospital_code", bindCardVo.getHospitalCode());

                MZPatient patient = createHisPatUser(jsonCard);

                if (patient == null) {
                    throw new CallException(ErrorCodeDefine.BIND_CARD_CREATE_USER, "HIS患者信息建档失败");
                }

                //获取患者信息
                logger.debug("根据建档信息，获取患者信息");
                hisPatient = queryHisPatUser(bindCardVo.getHospitalCode(), new Short(patient.getPatCardType()), patient.getPatCardNo(), "");

                if (hisPatient == null) {
                    throw new CallException(ErrorCodeDefine.BIND_CARD_VALUE, "根据建档信息，获取患者信息失败");
                }


            }

            logger.debug("patInfo:" + JsonUtils.toJsonString(hisPatient));

            //对于是身份证类型的参数，补全卡号和卡类型信息
            if (StringUtils.isBlank(bindCardVo.getCardNo())) {
                bindCardVo.setCardType(Short.parseShort(StringUtils.isBlank(hisPatient.getPatCardType()) ? "0" : hisPatient.getPatCardType()));
                bindCardVo.setCardNo(hisPatient.getPatCardNo());
            }

            //检查用户是否已经执行过绑卡
            if (!hasCheckMedicalExist) {
                //查询数据库是否已经有绑卡
                MedicalCardVo existMedicalCard = medicalCardDao.getMedicalCardByCardNo(bindCardVo.getHospitalCode(), bindCardVo.getCardNo(), (short) bindCardVo.getCardType().intValue());
                if (existMedicalCard != null) {
                    logger.warn("数据库已经存在绑卡记录:" + JsonUtils.toJsonString(existMedicalCard));
//					throw new CallException(ErrorCodeDefine.BIND_CARD_HAS_BINDED,"用户之前已经绑定");
                    return existMedicalCard;
                }
            }


            //检查用户是否已经存在
            PersonalUser personalUser = personalUserDao.getByIdCardNo(bindCardVo.getIdCardType(), bindCardVo.getIdCard());

            if (personalUser == null) {//如果用户不存在，生成用户信息
                logger.debug("bindCard:用户不存在，需要生成用户信息");
                personalUser = fillPersonalUser(hisPatient, bindCardVo);
                personalUserDao.insert(personalUser);
            } else {
                logger.debug("bindCard:用户已经存在，无需新增");
            }

            //进行绑卡
            //生成诊疗卡信息
            MedicalCard medicalCard = fillMedical(hisPatient, bindCardVo, personalUser, createCardFlag);
            medicalCardDao.insert(medicalCard);

            //平台用户
            PersonalUserOpenid existPersonalUserOpenid = personalUserOpenidDao.getByOpenIdAndAppId(bindCardVo.getOpenId(), orgApp.getId());
            if (existPersonalUserOpenid == null) {
                logger.debug("平台用户不存在，插入平台用户信息");
                PersonalUserOpenid personalUserOpenid = new PersonalUserOpenid();
                personalUserOpenid.setAppId(orgApp.getId());
                personalUserOpenid.setId(IDUtils.getUUID32());
                personalUserOpenid.setOpenId(bindCardVo.getOpenId());
                personalUserOpenid.setPerUserId(personalUser.getId());
                logger.debug("personalUserOpenid:" + JsonUtils.toJsonString(personalUserOpenid));

                personalUserOpenidDao.insert(personalUserOpenid);
            } else {
                logger.debug("平台用户已经存在，不插入平台用户信息");
            }

            return medicalCard;

        } catch (CallException ce) {
            logger.error("绑卡错误CallException：" + ce.toString());
            throw ce;
        } catch (Exception e) {
            logger.error("绑卡错误：" + ErrorCodeDefine.getStackTrace(e));
            throw new CallException(ErrorCodeDefine.BIND_CARD_COMMON, "绑卡异常", e);
        }
    }

    /**
     * 根据患者信息和调用入参，生成用户信息
     *
     * @param hisPatient HIS患者信息
     * @param bindCard   绑卡，调用入参
     * @return PersonalUser
     * @throws Exception
     */
    private PersonalUser fillPersonalUser(GetPatientInfoVoResponse hisPatient, BindCardVo bindCard) throws Exception {

        try {
            PersonalUser personalUser = new PersonalUser();

            personalUser.setId(IDUtils.getUUID32());

            //密码默认123456
            personalUser.setPassword("123456");

            personalUser.setAddress(hisPatient.getPatAddress());

            personalUser.setBirth(YYYYMMDD.format(YYYYMMDD8.parse(IdCardUtils.getBirthByIdCard(bindCard.getIdCard()))));

            personalUser.setEnableFlag((short) 1);

            //身份证
            personalUser.setIdCardNo(hisPatient.getPatIdNo());

            //件类型\r\n            1：二代身份证， \r\n            2：港澳居民身份证， \r\n            3：台湾居民身份证， \r\n            4：护照\r\n
            personalUser.setIdCardType(Short.parseShort(StringUtils.isBlank(hisPatient.getPatIdType()) ? "1" : hisPatient.getPatIdType()));

            //登陆名，默认手机，如果手机为空，则为身份证
            personalUser.setLoginName(StringUtils.isNotEmpty(hisPatient.getPatMobile()) ? hisPatient.getPatMobile() : hisPatient.getPatIdNo());

            personalUser.setMobile(hisPatient.getPatMobile());

            //昵称
            personalUser.setNickName(hisPatient.getPatName());

            personalUser.setRegisterTime(DateUtils.dateToString(new Date()));

            personalUser.setSex((short) ("M".equalsIgnoreCase(hisPatient.getPatSex()) ? 1 : 2));
            personalUser.setUserName(hisPatient.getPatName());

            //随机数，设置为和ID相同
            personalUser.setSalt(personalUser.getId());

//		personalUser.setAreaId(areaId);
//		personalUser.setAreaName(areaName);
//		personalUser.setCityId(cityId);
//		personalUser.setCityName(cityName);
//		personalUser.setDescription(description);
//		personalUser.setEmail(email);

//		personalUser.setProvinceId(provinceId);
//		personalUser.setProvinceName(provinceName);
//		personalUser.setQq(qq);

//		personalUser.setUserType(userType);
//		personalUser.setWechat(wechat);

            logger.debug("用户personalUser:" + JsonUtils.toJsonString(personalUser));
            return personalUser;
        } catch (Exception e) {
            logger.error("根据患者信息和调用入参，生成用户信息");
            throw new CallException(ErrorCodeDefine.BIND_CARD_VALUE, "根据患者信息和调用入参，生成用户信息" + e.toString(), e);
        }
    }

    /**
     * 生成诊疗卡信息
     *
     * @param hisPatient     HIS返回的患者信息
     * @param bindCard       绑卡调用入参
     * @param personalUser   用户信息
     * @param createCardFlag 是否进行了建档
     * @return 诊疗卡
     */
    private MedicalCard fillMedical(GetPatientInfoVoResponse hisPatient, BindCardVo bindCard, PersonalUser personalUser, boolean createCardFlag) {
        try {

            Org org = orgServiceImpl.getOrgByCode(bindCard.getHospitalCode());

            //进行绑卡
            MedicalCard medicalCard = new MedicalCard();

            medicalCard.setId(IDUtils.getUUID32());

            //诊疗卡号和类型
            medicalCard.setMedicalCardNo(hisPatient.getPatCardNo());
            medicalCard.setMedicalCardType(Short.parseShort(hisPatient.getPatCardType()));


            medicalCard.setEnableFlag((short) 1);
            medicalCard.setBeginCreatedTime(DateUtils.dateToString(new Date()));


            //1-微信\r\n    2-支付窗\r\n            3-APP应用
            medicalCard.setBindSourceFlag(bindCard.getPlatformType().shortValue());

            //0-绑定\r\n            1-建档
            medicalCard.setBindWay((short) (createCardFlag ? 0 : 1));
            medicalCard.setCreatedTime(DateUtils.dateToString(new Date()));

            /**
             * 监护者信息
             */
            medicalCard.setGuardAddress(hisPatient.getGuardAddress());
            medicalCard.setGuardId(hisPatient.getGuardIdNo());
            medicalCard.setGuardIdCardNo(hisPatient.getGuardIdNo());
            medicalCard.setGuardIdCardType(Short.parseShort(StringUtils.isBlank(hisPatient.getGuardIdType()) ? "1" : hisPatient.getGuardIdType()));
            medicalCard.setGuardMobile(hisPatient.getGuardMobile());
            medicalCard.setGuardName(hisPatient.getGuardName());

            //HIS端的patId
            medicalCard.setHisPatId(hisPatient.getPatId());

            //身份证
            medicalCard.setIdCardNo(hisPatient.getPatIdNo());

            //证件类型\r\n            1：二代身份证， \r\n            2：港澳居民身份证， \r\n            3：台湾居民身份证， \r\n            4：护照\r\n    S
            medicalCard.setIdCardType(Short.parseShort(StringUtils.isBlank(hisPatient.getPatIdType()) ? "1" : hisPatient.getPatIdType()));

            //组织信息，此即医院信息
            medicalCard.setOrgCode(bindCard.getHospitalCode());
            medicalCard.setOrgId(org.getId());
            medicalCard.setOrgName(org.getOrgName());

            medicalCard.setPatAddress(hisPatient.getPatAddress());

            if (StringUtils.isNotEmpty(hisPatient.getPatIdNo())) {
                medicalCard.setPatAge(IdCardUtils.getAgeByIdCard(hisPatient.getPatIdNo()));
            }

            //生日
            medicalCard.setPatBirth(hisPatient.getPatBirth());

            //手机
            medicalCard.setPatMobile(hisPatient.getPatMobile());

            //personalUser表的ID
            medicalCard.setPatId(personalUser.getId());
            //患者姓名
            medicalCard.setPatName(hisPatient.getPatName());

            //1-男\r\n            2-女\r\n
            medicalCard.setPatSex((short) ("M".equalsIgnoreCase(hisPatient.getPatSex()) ? 1 : 2));

//		medicalCard.setBindSourceAppCode(bindSourceAppCode);//######,暂时不填


//		medicalCard.setDescription(patInfo.get);
//		medicalCard.setEndCreatedTime(patInfo.get);
//		medicalCard.setAdmissionNo(patInfo.get);
//		medicalCard.setIsInsurance(patInfo.getGu);//####

//		medicalCard.setMedicareNo(patInfo.get);

            logger.debug("准备写入数据库的绑卡medicalCard:" + JsonUtils.toJsonString(medicalCard));

            return medicalCard;
        } catch (Exception e) {
            logger.error("生成诊疗卡信息失败");
            throw new CallException(ErrorCodeDefine.BIND_CARD_VALUE, "生成诊疗卡信息失败" + e.toString(), e);
        }
    }

    /**
     * 患者信息查询
     *
     * @param hospitalCode 医院编码
     * @param patCardType  诊疗卡类型   当有证件信息时，可以为空
     * @param patCardNo    诊疗卡号    当有证件信息时，可以为空
     * @param patName      患者姓名    当有卡号信息时，可以为空
     * @return 失败返回null或有异常抛出
     */
    private GetPatientInfoVoResponse queryHisPatUser(String hospitalCode, short patCardType, String patCardNo, String patName) {
        logger.debug("患者信息查询-外部接口-->");

        // 调用患者信息查询 yyt.hisiface.base.patient.info.get，如果是
        GetPatientInfoVoResponse patientInfo = null;
        Map<String, Object> queryMzPatientMap = new HashMap<String, Object>();
        queryMzPatientMap.put("hospital_code", hospitalCode);
//        queryMzPatientMap.put("branch_code", requestVo.getBranchCode());
        queryMzPatientMap.put("pat_name", patName);
        queryMzPatientMap.put("pat_card_type", patCardType);
        queryMzPatientMap.put("pat_card_no", patCardNo);


        logger.debug("查询参数：" + JsonUtils.toJsonString(queryMzPatientMap));
        Response mzPatientResponse = HisifaceService.callUnderlineFromInternal("yyt.hisiface.base.patient.info.get", JSON.toJSONString(queryMzPatientMap));
        logger.debug("查询结果" + JsonUtils.toJsonString(mzPatientResponse));

        if (!"0".equals(mzPatientResponse.getResultCode())) {
            logger.error("患者信息查询,没有有效结果");
//            throw new CallException(mzPatientResponse.getResultCode(), mzPatientResponse.getResultMessage());
            return null;
        }
        patientInfo = JsonUtils.parseObject(mzPatientResponse.getResult(), GetPatientInfoVoResponse.class);
        if (patientInfo == null || StringUtils.isBlank(patientInfo.getPatCardNo())) {
//        	throw new CallException(ErrorCodeDefine.BIND_CARD_VALUE, "查询患者信息失败，无卡号返回！");

            patientInfo = null;
        }

        logger.debug("患者信息:" + JsonUtils.toJsonString(patientInfo));

        return patientInfo;
    }

    /**
     * 患者信息建档
     *
     * @param cardRequest
     * @return 成功返回MZPatient对象（只包含卡号，卡类型，ID数据），失败返回null或抛出异常
     */
    private MZPatient createHisPatUser(Map<String, Object> cardRequest) {
        logger.debug("患者信息建档入口,参数：" + JsonUtils.toJsonString(cardRequest));
        Response mzPatientResponse = HisifaceService.callUnderlineFromInternal("yyt.hisiface.base.card.create", JsonUtils.toJsonString(cardRequest));
        logger.debug("结果" + JsonUtils.toJsonString(mzPatientResponse));

        if (!"0".equals(mzPatientResponse.getResultCode())) {
            logger.error("患者信息建档,HIS报告建档失败");
            throw new CallException(mzPatientResponse.getResultCode(), mzPatientResponse.getResultMessage());
        }
        MZPatient patient = JsonUtils.parseObject(mzPatientResponse.getResult(), MZPatient.class);
        if (patient == null || StringUtils.isBlank(patient.getPatCardNo())) {
            patient = null;
        }

        logger.debug("患者信息建档返回的患者信息:" + JsonUtils.toJsonString(patient));

        return patient;
    }

    /**
     * 获取就诊卡列表(新库)
     *
     * @param data
     * @return
     */
    public ResponseObject getBindCardLists(String data) {
        BindCardListVoRequest request = JsonUtils.parseObject(data, BindCardListVoRequest.class);
        ResponseObject response = new ResponseObject();

        if (StringUtils.isBlank(request.getOpenId())) {
            response.setResultCodeAndMessage("1001", "open_id不能空");
            return response;
        }
        //先找到openId 列表
        PersonalUserOpenid dBPerUserOpenid = personalUserOpenidDao.selectByOpenId(request.getOpenId(), request.getAppId());
        //先在opendId 表中找，若找不到openid，可能传进来的是userId 所以去personUser 表找
        if (dBPerUserOpenid !=null) {
            logger.info("传进来的是openId ={}", new Object[]{request.getOpenId()});
            List<String> personUserIds = new ArrayList<>();
            List<PersonalUser> personalUserList = new ArrayList<>();
            //通过openId 找到对应的用户列表
            personUserIds.add(dBPerUserOpenid.getPerUserId());
            logger.info("通过openId 找到的 personUserIds:=======" + personUserIds.size());
            if (CollectionUtils.isNotEmpty(personUserIds)) {
                //找到本人的记录
                personalUserList = personalUserDao.selectByIds(personUserIds);
            } else {
                response.setResultCodeAndMessage("1002", "open_id :" + request.getOpenId() + "下perUserId 为空");
                return response;
            }
            //通过用户找用户的关系人
            if (CollectionUtils.isNotEmpty(personalUserList)) {
                logger.info("通过personUserIds找到 personalUserList:={} 通过openId 找到的 personUserIds:={} ", new Object[]{personalUserList.size(), personUserIds.size()});
                List<String> personalUserIds = new ArrayList<>();
                for (PersonalUser personalUser : personalUserList) {
                    personalUserIds.add(personalUser.getId());
                }

                return getResponseObject(request, response, personalUserIds);

            } else {
                response.setResultCodeAndMessage("1002", "open_id :" + request.getOpenId() + "下perUserId 为空");
                return response;
            }

        } else {
            //在personUser 表找,此时  request.getOpenId() 可能是 userId
            logger.info("确认传进来来的是否是userId ==" + request.getOpenId());
            PersonalUser personalUser = personalUserDao.selectById(request.getOpenId());
            if (personalUser != null) {
                logger.info("通过userId ={}找到对应的person", new Object[]{request.getOpenId()});
                List<String> personalUserIds = new ArrayList<>();
                personalUserIds.add(personalUser.getId());
                return getResponseObject(request, response, personalUserIds);

            } else {
                response.setResultCodeAndMessage("1002", "userId :" + request.getOpenId() + "找不到对应的PersonUser");
                return response;
            }
        }
    }

    private ResponseObject getResponseObject(BindCardListVoRequest request, ResponseObject response, List<String> personalUserIds) {
        logger.info("personalUserIds====" + personalUserIds.toString());
        List<String> userIdList = new ArrayList<String>();
        List<MedicalCard> meidcalCards = new ArrayList<MedicalCard>();

        if (request.getOwnership() != null && request.getOwnership() == 1) {
            logger.info("查找本人的就诊卡列表开始");

            if (StringUtils.isNotEmpty(request.getFamilyId())){
                meidcalCards = medicalCardDao.selectSelfAllCard(request.getOpenId(),request.getFamilyId());
            }else {
                //本人的
                meidcalCards = medicalCardDao.selectByUserIdsAndBindSource(personalUserIds, request.getPlatformType(), request.getHospitalCode());
            }

            if (CollectionUtils.isEmpty(meidcalCards)) {
                MedicalCardResponse bindCardListVoResponse = new MedicalCardResponse();
                List<MedicalCardResponseVo> cardVoList = new ArrayList<>();
                bindCardListVoResponse.setCount(0);
                bindCardListVoResponse.setCardVoList(cardVoList);
                response.setResultCodeAndMessageAndResult("1002", "没有本人就诊卡信息", bindCardListVoResponse);
                return response;
            }

            logger.info("查找本人的就诊卡列表结束 meidcalCards.size = " + meidcalCards.size());
            uniqueMedicalCardList(meidcalCards);
            MedicalCardResponse bindCardListVoResponse = buildResponse(meidcalCards, null);
            response.setResultCodeAndMessageAndResult("0", "成功", bindCardListVoResponse);
            return response;


        } else if (request.getOwnership() != null && request.getOwnership() == 2) {
            logger.info("查找他人的就诊卡列表开始");

            List<PersonalUserRelation> personalUserRelations = personalUserRelationDao.selectByUserIds(personalUserIds);
            if (CollectionUtils.isEmpty(personalUserRelations)) {
                response.setResultCodeAndMessage("1002", "该用户没有关联其他关系人");
                return response;
            }

            Map<String, Short> perUserRelMap = new HashMap<>();
            for (PersonalUserRelation pr : personalUserRelations) {
                perUserRelMap.put(pr.getRelationPerUserId(), pr.getRelationType());
                userIdList.add(pr.getRelationPerUserId());
            }
            meidcalCards = medicalCardDao.selectByUserIdsAndBindSource(userIdList, request.getPlatformType(), request.getHospitalCode());
            if (CollectionUtils.isEmpty(meidcalCards)) {
                MedicalCardResponse bindCardListVoResponse = new MedicalCardResponse();
                List<MedicalCardResponseVo> cardVoList = new ArrayList<>();
                bindCardListVoResponse.setCount(0);
                bindCardListVoResponse.setCardVoList(cardVoList);
                response.setResultCodeAndMessageAndResult("1002", "该用户关联关系人没有绑卡", bindCardListVoResponse);
                return response;
            }
            uniqueMedicalCardList(meidcalCards);
            logger.info("查找他人的就诊卡列表结束");
            MedicalCardResponse bindCardListVoResponse = buildResponse(meidcalCards, perUserRelMap);
            response.setResultCodeAndMessageAndResult("0", "成功", bindCardListVoResponse);
            return response;

        } else {
            logger.info("查找所有人的就诊卡列表开始");
            List<PersonalUserRelation> personalUserRelations = personalUserRelationDao.selectByUserIds(personalUserIds);

            Map<String, Short> perUserRelMap = new HashMap<>();
            for (PersonalUserRelation pr : personalUserRelations) {
                perUserRelMap.put(pr.getRelationPerUserId(), pr.getRelationType());
                userIdList.add(pr.getRelationPerUserId());
            }
            for (String userId : personalUserIds) {
                userIdList.add(userId);
                perUserRelMap.put(userId, Short.valueOf("0"));
            }

            meidcalCards = medicalCardDao.selectByUserIdsAndBindSource(userIdList, request.getPlatformType(), request.getHospitalCode());
            if (CollectionUtils.isEmpty(meidcalCards)) {
                MedicalCardResponse bindCardListVoResponse = new MedicalCardResponse();
                List<MedicalCardResponseVo> cardVoList = new ArrayList<>();
                bindCardListVoResponse.setCount(0);
                bindCardListVoResponse.setCardVoList(cardVoList);
                response.setResultCodeAndMessageAndResult("1002", "该用户关联关系人没有绑卡", bindCardListVoResponse);
                return response;
            }

            logger.info("查找所有人的就诊卡列表开始");
            uniqueMedicalCardList(meidcalCards);
            MedicalCardResponse bindCardListVoResponse = buildResponse(meidcalCards, perUserRelMap);
            response.setResultCodeAndMessageAndResult("0", "成功", bindCardListVoResponse);
            return response;

        }
    }

    private void uniqueMedicalCardList(List<MedicalCard> medicalCards){
        Set<MedicalCard> medicalCardSet = new HashSet<MedicalCard>();
        for (MedicalCard med :medicalCards){
            medicalCardSet.add(med);
        }
        medicalCards.clear();
        medicalCards.addAll(medicalCardSet);
    }

    private MedicalCardResponse buildResponse(List<MedicalCard> meidcalCards, Map<String, Short> perUserRelMap) {
        logger.info("构建返回就诊卡列表开始");
        MedicalCardResponse bindCardListVoResponse = new MedicalCardResponse();
        bindCardListVoResponse.setCount(meidcalCards.size());
        List<MedicalCardResponseVo> cardVoList = new ArrayList<>();
        bindCardListVoResponse.setCardVoList(cardVoList);
        for (MedicalCard mc : meidcalCards) {
            MedicalCardResponseVo cardVo = new MedicalCardResponseVo();
            cardVo.setId(mc.getId());
            cardVo.setHospitalCode(mc.getOrgCode());
            cardVo.setHospitalName(mc.getOrgName());
            cardVo.setPatCardType(mc.getMedicalCardType());
            cardVo.setPatCardNo(mc.getMedicalCardNo());
            cardVo.setPatName(mc.getPatName());
            cardVo.setPatMobile(mc.getPatMobile());
            cardVo.setPatIdType(mc.getIdCardType());
            cardVo.setPatIdNo(mc.getIdCardNo());
            cardVo.setHisPatId(mc.getHisPatId());
            cardVo.setUserId(mc.getPatId());
            if (perUserRelMap != null) {
                cardVo.setOwnership(Short.valueOf(perUserRelMap.get(mc.getPatId())));
            }
            cardVoList.add(cardVo);
        }
        logger.info("构建返回就诊卡列表结束 response={}",new Object[]{JsonUtils.toJsonString(bindCardListVoResponse)});
        return bindCardListVoResponse;
    }


    public ResponseObject getBindCardList(String data) {
        BindCardListVoRequest request = JsonUtils.parseObject(data, BindCardListVoRequest.class);
        ResponseObject response = new ResponseObject();
        BindCardListVoResponse bindCardListVoResponse = new BindCardListVoResponse();
        String openId = request.getOpenId();
        String hospitalCode = request.getHospitalCode();
        Integer platformType = request.getPlatformType();
        Short ownerShip = request.getOwnership();
        if (StringUtils.isBlank(openId)) {
            response.setResultCodeAndMessage("1001", "open_id不能空");
            return response;
        }

        try (Connection con = DruidUtil.getConnection();
             Statement stmt = con.createStatement()) {

            String table = "biz_medical_card_";

            StringBuilder sb = new StringBuilder("select * from (");
            if (openId.length() != 32) {
                logger.info("通过openId ={}查找旧库绑卡数据", new Object[]{openId});
                String userTable ="eh_user_";
                StringBuilder userBuildSql =  new StringBuilder("select * from (");
                for (int i = 1; i <= 10; i++) {
                    userBuildSql.append("select * from ").append(userTable).append(i).append("  where account = '").append(openId).append("'");
                    if (i != 10) {
                        userBuildSql.append(" UNION ");
                    }
                }

                userBuildSql.append(") as allUser");
                String userSql = userBuildSql.toString();
                logger.info("userSql =" + userSql);

                try (ResultSet rs = stmt.executeQuery(userSql)) {
                    if (null != rs) {
                        while (rs.next()) {
                           openId = rs.getString("ID");
                        }
                    }
                }
                logger.info("通过opend_id查询到的userId={}",openId);
            }

            if (openId !=null){
                for (int i = 1; i <= 10; i++) {
                    sb.append("select * from ").append(table).append(i).append("  where user_id = '").append(openId).append("'");
                    sb.append(" and state =1 ");


                    if (!StringUtils.isBlank(hospitalCode)) {

                        if (OrgCodeMap.hospitalCodeMap.get(hospitalCode) != null) {
                            sb.append(OrgCodeMap.hospitalCodeMap.get(hospitalCode));
                        } else {
                            sb.append(" and hospital_code = '").append(hospitalCode).append("'");
                        }

                    }

                    if (ownerShip != null) {
                        sb.append("and ownership = '").append(ownerShip).append("'");
                    }
                    if (i != 10) {
                        sb.append(" UNION ");
                    }
                }

                sb.append(") as allCard");

                String sql = sb.toString();

                logger.info("Sql =" + sql);
                List<CardVo> cardVoList = new ArrayList<>();

                try (ResultSet rs = stmt.executeQuery(sql)) {
                    if (null != rs) {
                        while (rs.next()) {
                            CardVo cardVo = new CardVo();
                            cardVo.setMedicalCardId(rs.getString("ID"));

                            cardVo.setHospitalCode(rs.getString("HOSPITAL_CODE"));
                            cardVo.setHospitalName(rs.getString("HOSPITAL_NAME"));
                            cardVo.setPatCardType(Short.valueOf(rs.getString("CARD_TYPE")));
                            cardVo.setPatCardNo(rs.getString("CARD_NO"));
                            cardVo.setPatName(rs.getString("NAME"));
                            cardVo.setPatMobile(rs.getString("MOBILE"));
                            cardVo.setIdCardType(Short.valueOf(rs.getString("ID_TYPE")));
                            cardVo.setIdCard(rs.getString("ID_NO"));
                            cardVo.setOwnership(Integer.valueOf(rs.getString("OWNERSHIP")));
                            cardVoList.add(cardVo);
                        }
                    }
                }
                logger.info("cardVoList.size() == " + cardVoList.size());
                bindCardListVoResponse.setCount(cardVoList.size());
                bindCardListVoResponse.setCardVoList(cardVoList);
                response.setResultCodeAndMessageAndResult("0", "成功", bindCardListVoResponse);
            }else {
                response.setResultCodeAndMessage("1001", "user_id为空");

            }

        } catch (SQLException e) {
            response.setResultCodeAndMessageAndResult("0", "失败", null);
            logger.error("[DBUtil -> SQLException]", e);
        }
        return response;
    }


}
